#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include"common.hpp"
#define PATH "."
#define FILENAME "fifo"



class NameFifo
{
public:
    NameFifo(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        _fifoname = _path + "/" + _name;
        umask(0);  
        // 新建管道
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
        {
            ERR_EXIT("mkfifo");
        }
        else
        {
            std::cout << "mkfilo sucess" << std::endl;
        }
    }
    ~NameFifo()
    {
        // 删除管道文件
        int n = unlink(_fifoname.c_str());
        if (n < 0)
        {
            ERR_EXIT("unlink");
        }
        else
        {
            std::cout << "remove fifo sucess" << std::endl;
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

class FileOper
{

public:
    FileOper(const std::string &path, const std::string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + "/" + _name;
    }

    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open");
        }
        else
        {
            std::cout << "open fifo sucess" << std::endl;
        }
    }

    void OpenForRead()
    {
        // 打开，write方没有执行open的时候，read方，就要在open内部进行阻塞
        // 直到有人把管道文件打开了，open才会返回！
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open");
        }
        else
        {
            std::cout << "open fifo sucess" << std::endl;
        }
    }

    bool WakeUp()
    {
        char ch='w';
        int n=write(_fd,&ch,1);
        if(n>0)
        {
            printf("尝试唤醒: %d\n", n);
            return true;
        }
        else
        {
            return false;
        }
    }

    bool Wait()
    {
        char ch;
        int n=read(_fd,&ch,1);
        if(n>0)
        {
            printf("醒来: %d\n", n);
            return true;
        }
        else
        {
            return false;
        }
    }
    void Close()
    {
        if (_fd > 0)
            close(_fd);
    }
    ~FileOper() {}

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};